package com.zq.daoImpl;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.springframework.stereotype.Repository;

import com.zq.dao.BaseDao_zq;
import com.zq.dao.DeptDao;
import com.zq.page.Page;
import com.zq.pojo.Dept;
@Repository("deptDao")
public class DeptDaoImpl extends BaseDao_zq implements DeptDao{
	/*private SessionFactory sessionFactory;
	public DeptDaoImpl()
	{
		sessionFactory = HibernateSessionFactory.getSessionFactory();
	}*/
	
	//增
	@Override
	public void add(Dept dept) throws Exception {
		// TODO Auto-generated method stub
		Session session = getSession();
		
		session.save(dept);
		session.close();
	}
	//删
	@Override
	public void delete(Dept dept)throws Exception {
		// TODO Auto-generated method stub
		Session session = getSession();
		Transaction transaction = session.beginTransaction();
		session.delete(dept);
		transaction.commit();
		session.close();
	}
	//改
	@Override
	public void update(Dept dept) throws Exception{
		// TODO Auto-generated method stub
		Session session = getSession();
		Transaction transaction = session.beginTransaction();
		session.saveOrUpdate(dept);
		transaction.commit();
		session.close();
	}
	//查一条
	@Override
	public Dept findByDeptno(int deptNo) throws Exception{
		// TODO Auto-generated method stub
		Session session = getSession();
		String hql = "from Dept where deptNo=?";
		Dept dept = (Dept) session.createQuery(hql).setParameter(0, deptNo).uniqueResult();
		session.close();
		return dept;
	}
	//查所有
	@SuppressWarnings("unchecked")
	@Override
	public List<Dept> findAllDepts()throws Exception {
		Session session = getSession();
		String hql = "from Dept";
		List<Dept> depts = session.createQuery(hql).list();
		session.close();
		return depts;
	}
	//模糊查找
	@SuppressWarnings("unchecked")
	@Override
	public List<Dept> findByDeptNames(String deptName) throws Exception{
		Session session = getSession();
		String hql = "from Dept where deptName like ?";
		List<Dept> depts = session.createQuery(hql).setParameter(0, "%"+deptName+"%").list();
		session.close();
		return depts;
	}
	@SuppressWarnings("unchecked")
	@Override
	public List<Dept> findAll(int pageNo) throws Exception{
		Session session = getSession();
		String hql = "from Dept";
		List<Dept> depts = session.createQuery(hql).setFirstResult((pageNo - 1)* 3).setMaxResults(3).list();
		session.close();
		return depts;
	}
	@Override
	public Page<Dept> getPage(int pageNo) throws Exception{
		Page<Dept> page = new Page<>();
		page.setPageNo(pageNo);
		page.setTotalNum(getTotalNum());
		page.setList(findAll(page.getPageNo()));
		return page;
	}
	@Override
	public int getTotalNum() throws Exception{
		Session session = getSession();
		String sql = "SELECT COUNT(*) FROM t_dept";
		Object obj = session.createSQLQuery(sql).uniqueResult();
		int a = -1;
		if(obj != null){
			a = Integer.parseInt(obj.toString());
		}
		session.close();
		System.out.println("a=" + a);
		return a;
		
	}
	

}
